from rest_framework import serializers
from goods.models import SKU

class CartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1,
                                      label='商品编号')
    count = serializers.IntegerField(min_value=1,
                                     max_value=200,
                                     label='商品数量')
    selected = serializers.BooleanField(default=True,
                                        label='是否选中',
                                        required=False)

    # 多字段校验
    def validate(self, attrs):
        # 获取数据
        sku_id = attrs['sku_id']
        count = attrs['count']
        selected = attrs['selected']

        # 判断商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")
        # 判断商品数量是否大于库存量
        if count > sku.stock:
            raise serializers.ValidationError('库存量不足')

        return attrs

    def validate_sku_id(self, sku_id):
        # 获取sku_id对应的对象是否存在
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError('商品不存在')

        return sku_id

